<template>
  <el-row>
    <el-col :span="24"><h1>专业管理</h1></el-col>
  </el-row>
  <el-row>
    <el-col :span="16">
      <el-button type="success" :size="'default'" @click="dialogVisible = true">新增专业</el-button>
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column prop="id" label="专业代号" width="500"/>
        <el-table-column prop="name" label="专业名称" width="500"/>
        <el-table-column>
          <template v-slot="scope">
            <el-button type="danger" :size="'small'" @click="deleteMajorityInfo(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-col>
  </el-row>
  <br><br>
  <el-row>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :background="true"
        layout="prev, pager, next, jumper"
        :total="total"
        @current-change="handleCurrentChange"
    />
  </el-row>

  <el-dialog
      v-model="dialogVisible"
      title="新增专业"
      width="400"
  >
    <el-form :model="newMajority" label-width="auto" style="max-width: 300px" :size="'default'" :rules="rule">
      <el-form-item label="专业名称" prop="name">
        <el-input v-model.number="newMajority.name" />
      </el-form-item>
      <el-button type="primary" @click="addMajorityInfo" :size="'default'">新增</el-button>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">

//当前页号
import {onMounted, reactive, ref} from "vue";
import {Majority} from "@/api/types/majority.ts";
import {addMajority, deleteMajority, getAllMajority} from "@/api/majority.ts";
import {ElMessage, FormRules} from "element-plus";

onMounted(() => {
  getAllMajority().then(data => {
    totalDate.value = data.data
    handleCurrentChange(currentPage.value)
  })
})

const rule = reactive<FormRules<Majority>> ({
  name: [
    {required: true, message: '请输入专业名', trigger: 'blur'}
  ],
})



const newMajority = reactive<Majority>({
  id: 0,
  name: ''
})

//对话框开启条件
const dialogVisible = ref(false)

const currentPage = ref(1)
//记录总数
const total = ref(0)
//一页的记录数
const pageSize = ref(7)

//所有数据
const totalDate = ref<Majority[]>(
    []
)

//当前页的数据
const tableData = ref<Majority[]>(
    []
)

const handleCurrentChange = (val: number) => {
  var startIndex = (val - 1) * pageSize.value
  total.value = <number>totalDate.value?.length
  tableData.value = totalDate.value?.slice(startIndex, startIndex + pageSize.value)
}

const deleteMajorityInfo = (rowId: number) => {
  deleteMajority(tableData.value[rowId]).then(data => {
    if (data.code == 300) {
      totalDate.value = data.data
      handleCurrentChange(currentPage.value)
    }
    ElMessage(data.msg)
  })
}

const addMajorityInfo = () => {
  addMajority(newMajority).then(data => {
    if (data.code == 300) {
      totalDate.value = data.data
      handleCurrentChange(currentPage.value)
      dialogVisible.value = false
    }
    ElMessage(data.msg)
  })
}


</script>

<style scoped>

</style>
